package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.constant.MessageConstant;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.entity.Result;
import com.itheima.pojo.Member;
import com.itheima.service.MemberService;
import org.apache.ibatis.annotations.Param;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.aspectj.weaver.ast.Var;
import org.springframework.scheduling.support.SimpleTriggerContext;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.swing.*;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;


/**
 * 会员管理
 */
@RestController
@RequestMapping("/member")
public class MemberController {

    @Reference
    private MemberService memberService;


    //添加数据
    @RequestMapping("/add")
    public Result add(@RequestBody Member member) {
        try {
            Date date = new Date();
            member.setRegTime(date);
            memberService.add(member);
            return new Result(true, MessageConstant.ADD_MEMBER_SUCCESS);

        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.ADD_MEMBER_FAIL);
        }

    }

    //分页查询
    @RequestMapping("/findPage")
    //@PreAuthorize("hasAuthority('MEMBER_QUERY')")//权限校验
    public PageResult findPage(@RequestBody QueryPageBean queryPageBean) {
        return memberService.findPage(queryPageBean);
    }


    //根据id删除检查项
    @RequestMapping("/delete")
    public Result delete(Integer id) {
        try {
            memberService.delete(id);//发送请求
            return new Result(true, MessageConstant.DELETE_MEMBER_SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.DELETE_MEMBER_FAIL);
        }
    }


    //根据id查询检查项
    @RequestMapping("/findById")
    public Result findById(Integer id) {
        try {
            Member member = memberService.findById(id);//发送请求
            return new Result(true, MessageConstant.QUERY_SETMEAL_SUCCESS, member);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.QUERY_SETMEAL_FAIL);
        }
    }


    @RequestMapping("/edit")
    public Result edit(@RequestBody Member member) {
        try {
            memberService.edit(member);//发送请求
            return new Result(true, MessageConstant.EDIT_MEMBER_SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.EDIT_MEMBER_FAIL);
        }
    }

    @RequestMapping("/getNames")
    public Result getNames() {
        try {
            List<String> list = memberService.getNames();
            return new Result(true, MessageConstant.GET_USER_SUCCESS, list);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.GET_USER_FAIL);
        }
    }

    @RequestMapping("/exportExcel")
    public void exportExcel(HttpServletRequest request, HttpServletResponse response, Integer[] ids) throws IOException, InvalidFormatException {


        ArrayList<Member> members = new ArrayList<>();
        for (Integer id : ids) {
            Member member = memberService.findById(id);
            members.add(member);
        }
        String template = request.getSession().getServletContext().getRealPath("template");
        String path = template + File.separator + "member_info_template.xlsx";
        File file = new File(path);
        XSSFWorkbook workbook = new XSSFWorkbook(file);
        XSSFSheet sheet = workbook.getSheetAt(0);

        for (int i = 0; i < members.size(); i++) {
            String fileNumber = members.get(i).getFileNumber();
            String name = members.get(i).getName();
            String sex = members.get(i).getSex();
            String birthday = null;
            if (members.get(i).getBirthday() != null) {
                birthday = new SimpleDateFormat("yyyy-MM-dd").format(members.get(i).getBirthday());
            }
            String manager = members.get(i).getManager();
            String regtime = null;
            if (members.get(i).getRegTime() != null) {
                regtime = new SimpleDateFormat("yyyy-MM-dd").format(members.get(i).getRegTime());
            }
            String phoneNumber = members.get(i).getPhoneNumber();
            sheet.getRow(i+1).getCell(0).setCellValue(fileNumber == null ? "" : fileNumber);
            sheet.getRow(i+1).getCell(1).setCellValue(name == null ? "" : name);
            sheet.getRow(i+1).getCell(2).setCellValue(sex == null ? "" : sex);
            sheet.getRow(i+1).getCell(3).setCellValue(birthday == null ? "" : birthday);
            sheet.getRow(i+1).getCell(4).setCellValue(manager == null ? "" : manager);
            sheet.getRow(i+1).getCell(5).setCellValue(regtime == null ? "" : regtime);
            sheet.getRow(i+1).getCell(6).setCellValue(phoneNumber == null ? "" : phoneNumber);

        }


        ServletOutputStream os = response.getOutputStream();
        response.setHeader("content-Disposition", "attachment;filename=report.xlsx");
        response.setContentType("application.vnd.ms-excel");
        workbook.write(os);

        os.flush();
        os.close();
        workbook.close();
    }


}
